// 1.引入axios
import Axios from 'axios'
import store from '../store'
import router from '@/router'

// 2.创建aixos实例
const axios = Axios.create({
  // 配置基地址
  baseURL: 'http://toutiao.itheima.net',
  // 设置超时时间
  timeout: 20000
})

// 3.导出aixos
export default ({ url, method = 'GET', params, data, headers }) => {
  return axios({
    url: url,
    method: method,
    params: params,
    data: data,
    headers
  })
}

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  if (store.state.token.length > 0 && config.headers.Authorization === undefined) {
    config.headers.Authorization = 'Bearer ' + store.state.token
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response
}, function (error) {
  // 对响应错误做点什么
  if (error.response.status === 401) {
    store.commit('setToken', '')
    router.push({ path: '/login' })
  }
  return Promise.reject(error)
})
